package com.example.demo;

import java.util.List;

import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {

    @Results({ @Result(property = "name", column = "name"), @Result(property = "age", column = "age") })
    @Select("SELECT name, age FROM user")
    List<User> findAll();

    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER(NAME, AGE, EMAIL) VALUES(#{name}, #{age}, #{email})")
    int insert(@Param("name") String name, @Param("age") Integer age, @Param("email") String email);

    @Update("UPDATE user SET age=#{age} WHERE name=#{name}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Long id);

    // 新方法：根据可选的 name 或 email 查询
    @Select({
        "<script>",
            "SELECT * FROM USER",
            "<where>",
                "<if test='name != null and name != \"\"'>",
                    "AND NAME = #{name}",
                "</if>",
                "<if test='email != null and email != \"\"'>",
                    "AND EMAIL = #{email}",
                "</if>",
            "</where>",
        "</script>"
    })
    List<User> findByOptionalParams(@Param("name") String name, @Param("email") String email);
}
